package com.aduerr.v1shouyin.mvp.fragment;


import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import com.aduerr.v1shouyin.App;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.entity.KaQuanXiangQingEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.mvp.activity.BangGuidActivity;
import com.aduerr.v1shouyin.mvp.activity.LoginActivity;
import com.aduerr.v1shouyin.mvp.adpter.KaqaunhexiaoStickrecycleadpter;
import com.aduerr.v1shouyin.util.PeixiDividerGridItemDecoration;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.internal.observers.BlockingBaseObserver;
import io.reactivex.schedulers.Schedulers;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.HashMap;

/**
 * 平台卡券核销
 * <p>
 * Created by fyf on 2018/6/6 0006.
 */

public class KaquanHeXiaoFragment extends Fragment {

    public static final String TAG = "KaquanHeXiaoFragment";
    @BindView(R.id.recyclerview_kaquan)
    RecyclerView recyclerviewKaquan;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;

    private KaqaunhexiaoStickrecycleadpter kaqaunhexiaoStickrecycleadpter;
    private int page = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_kaquanhexiao, null, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initdate();
    }

    private void initdate() {
        recyclerviewKaquan.setLayoutManager(new LinearLayoutManager(getContext(),
                RecyclerView.VERTICAL, false));
        recyclerviewKaquan.addItemDecoration(new PeixiDividerGridItemDecoration(getContext(), PeixiDividerGridItemDecoration.VERTICAL_LIST,
                8, R.color.bg_ios));
        kaqaunhexiaoStickrecycleadpter = new KaqaunhexiaoStickrecycleadpter(getContext());
        StickyRecyclerHeadersDecoration headersDecor =
                new StickyRecyclerHeadersDecoration(kaqaunhexiaoStickrecycleadpter);
        //绑定之前的adapter

        kaqaunhexiaoStickrecycleadpter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                headersDecor.invalidateHeaders();
            }
        });
        recyclerviewKaquan.addItemDecoration(headersDecor);
        recyclerviewKaquan.setAdapter(kaqaunhexiaoStickrecycleadpter);

        refreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initData(1);
                        refreshlayout.finishRefresh();
                        refreshlayout.setLoadmoreFinished(false);
                    }
                }, 2000);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(final RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page++;
                        initData(page);
                        refreshlayout.finishLoadmore();

                    }
                }, 2000);
            }
        });
        //触发自动刷新
        refreshLayout.autoRefresh();
    }

    private void initData(int i) {

        HashMap<String, String> addParams = new HashMap<>();
//        addParams.put("scanticketno", erWeiMaResult);//86008032893055438199  test
        addParams.put("page", i + "");
        APIRetrofit.getAPIService().getKaQuanXiangQingDetail(RXRequest.getXingPosParams(addParams, getActivity()))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<KaQuanXiangQingEntity>() {
                    @Override
                    public void onNext(KaQuanXiangQingEntity kaQuanXiangQingEntity) {
                        int success = kaQuanXiangQingEntity.getSuccess();
                        if(success == 1) {
                            int pageIndex = kaQuanXiangQingEntity.getPageIndex();
                            if(pageIndex > 1) {
//                                List<KaQuanXiangQingEntity.DataBean> data =
//                                kaQuanXiangQingEntity.getData();
                                kaqaunhexiaoStickrecycleadpter.loadmore(kaQuanXiangQingEntity.getData());
                            } else {
                                kaqaunhexiaoStickrecycleadpter.refresh(kaQuanXiangQingEntity.getData());
                            }

                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(getActivity(), "autologin");
                            SharedPreferencesUtils.remove(getActivity(),
                                    "remberpassword");
                            startActivity(new Intent(getContext(),
                                    BangGuidActivity.class));

                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(kaQuanXiangQingEntity.getErrMsg());
                            SharedPreferencesUtils.remove(getActivity(), "autologin");
                            SharedPreferencesUtils.remove(getActivity(),
                                    "remberpassword");
                            startActivity(new Intent(getContext(), LoginActivity.class));

                        } else if(success == -4) {
                            //没有成功
                            String erMsg = kaQuanXiangQingEntity.getErrMsg();
                            ToastUtils.showToast(getContext(), erMsg + "");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(App.getApp(), "网络连接超时", Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(App.getApp(), "连接失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(App.getApp(), "检查网络状态", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
